<?php

namespace App\Models\Admin;

use Illuminate\Database\Eloquent\Model;
use App\Models\BaseModel;
use App\Models\Admin\OrderItem;
use App\Models\Admin\Store;
use App\Common\AliossHandler;
use App\Common\ValidateHandler;
use App\Exports\OrderExport;
use Auth, Excel;
use Carbon\Carbon;
use App\Models\Admin\ReviewOrder;

class Order extends BaseModel
{
    protected $fillable = [
        'id', 'user_id', 'store_id', 'order_code', 'pay_user_id',
        'order_status', 'type', 'accepter_name', 'accepter_phone', 'province_name',
        'city_name', 'district_name', 'detail_address', 'national_code', 'express_type',
        'express_weight', 'express_price', 'express_number', 'base_price', 'cost_price',
        'pay_price', 'jf_price', 'jf', 'express_at', 'cancel_at',
        'pay_at', 'send_at', 'accept_at', 'created_at', 'updated_at', 'status'
    ];
    
    public function getList($pageSize, $orderId, $orderCode, $orderStatus, $userId, $requestStoreId, $acceptUser, $report)
    {
        $storeId = Auth::guard('admin')->user()->store_id;
        $sql = $this;
        if(!empty($orderId)) {
            $sql = $sql->where('id', $orderId);
        }
        if(!empty($orderCode)) {
            $sql = $sql->where('order_code', $orderCode);
        }
        if($orderStatus != 100) {
            $sql = $sql->where('order_status', $orderStatus);
        }
        if(!empty($userId)) {
            $sql = $sql->where('user_id', $userId);
        }
        if(!empty($acceptUser)) {
            $sql = $sql->where('accepter_name', $acceptUser);
        }

        if ($storeId == 0) {
            // 管理员查看全部店铺订单
            if ($requestStoreId == 0) {
                $sql = $sql->orderBy('store_id', 'asc')->orderBy('created_at', 'desc');
            } else {
                $sql = $sql->where('store_id', $requestStoreId)->orderBy('created_at', 'desc');
            }

        } else {
            // 店家只能查看自己店的订单
            $sql = $sql->where('store_id', $storeId)->orderBy('store_id');
        }

        if(!empty($report)) {
            $data = $sql->get()->toArray();
            $data = $this->handleImportOrderData($data);
            return Excel::download(new OrderExport($data), 'order.xlsx');
        }

        $data = $sql->paginate($pageSize)->toArray();
        $data = $this->handleOrderData($data);
        return $this->success($data);
    }

    private function handleImportOrderData($data)
    {
        $arr = [];
        $store = new Store;
        foreach($data as $k => $order) {
            $orderItems = $this->orderItem($order['id']);
            foreach($orderItems as $orderItem)
            {
                $item = [];
                $item['id'] = $order['id'];
                // $item['pay_price'] = $order['pay_price']/100;
                // $item['express_price'] = $order['express_price']/100;
                $item['user_id'] = $order['user_id'];
                $item['good_title'] = $orderItem['good_title'].'('.$orderItem['good_describe'].')';
                $item['good_num'] = $orderItem['goods_quantity'];
                // $item['good_price'] = $orderItem['pay_price'];
                $item['order_status'] = $this->getOrderStatusText($order['order_status']);
                $item['created_at'] = $order['created_at'];
                $item['pay_at'] = $order['pay_at'];
                $item['accepter_name'] = $order['accepter_name'];
                $item['accepter_phone'] = $order['accepter_phone'];
                $item['province_name'] = $order['province_name'];
                $item['city_name'] = $order['city_name'];
                $item['district_name'] = $order['district_name'];
                $item['detail_address'] = $order['detail_address'];
                array_push($arr, $item);
            }
        }

        return $arr;
    }

    private function handleOrderData($data)
    {
        $store = new Store;
        foreach($data['data'] as $k => $order) {
            $data['data'][$k]['order_items'] = $this->orderItem($order['id']);
            $data['data'][$k]['store'] = $store->getStoreText($order['store_id']);
        }

        return $data;
    }

    private function getOrderGoodInfo($orderId)
    {
        $items = $this->orderItem($orderId);
        $arr['name'] = '';
        $arr['price'] = '';
        $arr['sum'] = '';
        foreach($items as $item)
        {
            $arr['name'] .= "（".$item['good_title']."）";
            $arr['price'] .= "（".$item['pay_price']."）";
            $arr['sum'] .= "（".$item['goods_quantity']."）";
        }
        return $arr;
    }

    private function getOrderStatusText($status)
    {
        $text = '';
        switch($status){
            case 0:
                $text = "超时取消";
                break;
            case 1:
                $text = "已取消";
                break;
            case 2:
                $text = "待付款";
                break;
            case 3:
                $text = "待发货";
                break;
            case 4:
                $text = "待收货";
                break;
            case 5:
                $text = "已收货";
                break;
            case 6:
                $text = "退款中";
                break;
            case 7:
                $text = "已退款";
                break;
        }

        return $text;
    }

    public function orderItem($orderId){
        $item = OrderItem::where('order_id', $orderId)->get()->toArray();
        foreach($item as $k => $value){
            $item[$k]['cover'] = AliossHandler::read('good', $value['good_logo']);
            $item[$k]['pay_price'] = $value['pay_price'] / 100;
        }

        return $item;

    }

    public function handle($id, $data)
    {
        $result = $this->validate($data);
        if (!$result['res']) {
            return $this->error($result);
        }

        $order = $this->find($id);
        if($order->order_status < 3 || $order->order_status > 4) {
            return $this->error(['res' => false, 'info' => "订单状态错误"]);
        }

        $order->express_number = $data;
        $order->order_status = 4;
        $order->send_at = date('Y-m-d H:i:s');
        $order->save();

        return $this->success(['info' => '操作成功']);
    }

    private function validate($data)
    {
        $arr = [
            0 => [
                'name' => '运单号',
                'value' => $data,
                'func' => 'is_empty'
            ]
        ];
        return ValidateHandler::do($arr);
    }


    public function getSendList($pageSize, $orderId, $orderCode, $userId, $requestStoreId, $acceptUser, $report)
    {
        $storeId = Auth::guard('admin')->user()->store_id;
        $sql = $this;
        
        if(!empty($orderId)) {
            $sql = $sql->where('id', $orderId);
        }
        if(!empty($orderCode)) {
            $sql = $sql->where('order_code', $orderCode);
        }

        //默认  显示待发货状态 
        $sql = $sql->where('order_status', 3);
        if(!empty($userId)) {
            $sql = $sql->where('user_id', $userId);
        }
        if(!empty($acceptUser)) {
            $sql = $sql->where('accepter_name', $acceptUser);
        }
        $today = Carbon::now();
        $end = Carbon::create($today->year,$today->month,$today->day,15,0,0);
        $sql = $sql->where('pay_at','<',$end);
        if ($storeId == 0) {
            // 管理员查看全部店铺订单
            if ($requestStoreId == 0) {
                $sql = $sql->orderBy('store_id', 'asc')->orderBy('pay_at', 'desc');
            } else {
                $sql = $sql->where('store_id', $requestStoreId)->orderBy('pay_at', 'desc');
            }

        } else {
            // 店家只能查看自己店的订单
            $sql = $sql->where('store_id', $storeId)->orderBy('store_id');
        }

        if(!empty($report)) {
            $data = $sql->get()->toArray();
            $data = $this->handleImportOrderData($data);
            return Excel::download(new OrderExport($data), '维康宝订单'.date('Ymd').'.xlsx');
        }

        $data = $sql->paginate($pageSize)->toArray();
        $data = $this->handleOrderData($data);
        return $this->success($data);
    }

    public function reviewOrder($request,$path=''){
        // 读取店铺ID
        $user = Auth::guard('admin')->user();
        if ($user->store_id === 0) {
            // 超管必需选择店铺
            $storeId = $request['storeId'];
            if (empty($storeId)) {
                return $this->error(['info' => '请输入店铺ID']);
            }
        } else {
            // 否则 获取用户本身代表的店铺
            $storeId = $user->store_id;
        }
        $review = new ReviewOrder;
        $info = $review->where('store_id',$storeId)->first();
        $orderIds = [];
        if(!empty($info->content)){
            $orderIds = explode(',',$info->content);
        }

        $arr = $this->join('order_items as i','i.order_id','=','orders.id')
        ->whereIn('orders.id',$orderIds)
        ->get()
        ->toArray();

        $title = Store::where('id',$storeId)->first()->title;
        $statistics = [];
        foreach ($arr as $key => $value) {
            $arr[$key]['store_title'] = $title;
            if(!isset($statistics[$value['good_id']])){
                $statistics[$value['good_id']] = [];
                $statistics[$value['good_id']]['title'] = $value['good_title'].'('.$value['good_describe'].')';
                $statistics[$value['good_id']]['num'] = $value['goods_quantity'];
                $statistics[$value['good_id']]['good_id'] = $value['good_id'];
            }else{
                $statistics[$value['good_id']]['num'] += $value['goods_quantity'];
            }
        }

        $info = [];
        foreach ($statistics as $key => $value) {
            array_push($info,$value);
        }
        $data = [];
        $data['data'] = $arr; 
        $data['path'] = $path;
        $data['statistics'] = $info;
        return $this->success($data);
    }
}
